package dao

import (
	"context"
	"gorm.io/gorm"
	"ylm.sl/global"
	"ylm.sl/internal/model"
)

type UserDao struct {
	db *gorm.DB
}

func (d *UserDao) Insert(ctx context.Context, entity model.User) error {
	err := d.db.WithContext(ctx).Create(&entity).Error
	if err != nil {
		global.Log.ErrContext(ctx, "UserDao.insert failed, err: %v", err)
		return err
	}
	return nil
}

func (d *UserDao) SelectByUsernameAndPassword(ctx context.Context, username string, password string) (*model.User, error) {
	entity := &model.User{}

	err := d.db.WithContext(ctx).First(entity, "username = ? and password = ?", username, password).Error
	if err != nil {
		global.Log.ErrContext(ctx, "UserDao.SelectByUsernameAndPassword failed, err: %v", err)
		return nil, err
	}
	return entity, nil
}

func (d *UserDao) SelectByUsername(ctx context.Context, username string) (*model.User, error) {
	entity := &model.User{}

	err := d.db.WithContext(ctx).First(entity, "username = ?", username).Error
	if err != nil {
		global.Log.ErrContext(ctx, "UserDao.SelectByUsername failed, err: %v", err)
		return nil, err
	}
	return entity, err
}

func (d *UserDao) Update(ctx context.Context, entity model.User) error {

	err := d.db.WithContext(ctx).Model(&entity).Updates(entity).Error
	if err != nil {
		global.Log.ErrContext(ctx, "UserDao.Update failed, err: %v", err)
		return err
	}

	return nil
}

func NewUserDao(db *gorm.DB) *UserDao {
	return &UserDao{db: db}
}
